package Week.D008;

import org.junit.Test;

import java.util.*;
import java.util.Map;

public class Solution02 {

    public List<String> beforeAndAfterPuzzles2(String[] phrases) {

        Map<String, String> map = new HashMap<>();
        for (String phrase : phrases) {
            int index = phrase.indexOf(" ");
            String key;
            String value;
            if (index != -1) {
                key = phrase.substring(0, index);
                value = phrase.substring(index + 1);

            } else {
                key = phrase;
                value = "";
            }
            map.put(key, value);
        }
        List<String> result = new ArrayList<>();
        for (String phrase : phrases) {
            int lastIndex = phrase.lastIndexOf(" ");
            String lastKey;
            if (lastIndex != -1) {
                lastKey = phrase.substring(lastIndex + 1);

            } else {
                lastKey = phrase;
            }

            if (map.containsKey(lastKey)) {
                result.add((phrase + " " + map.get(lastKey)).trim());
            }

        }
        Collections.sort(result);
        return result;

    }


    public List<String> beforeAndAfterPuzzles(String[] phrases) {

        Set<String> res = new TreeSet<>();
        Map<String, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < phrases.length; i++) {
            String s = phrases[i];
            String s1 = getStart(s);
            if (!map.containsKey(s1)) {
                map.put(s1, new ArrayList<>());
            }
            map.get(s1).add(i);
        }
        for (int i = 0; i < phrases.length; i++) {
            String s = phrases[i];
            String key = getEnd(s);
            if (!map.containsKey(key)) continue;
            for (int j : map.get(key)) {
                if (i == j) continue;
                String result = s + help(phrases[j]);
                res.add(result);
            }
        }
        List<String> ans = new ArrayList<>(res.size());
        ans.addAll(res);
        return ans;
    }

    private String help(String phrase) {
        if (phrase.contains(" ")) return phrase.substring(phrase.indexOf(" "));
        else return "";
    }

    private String getEnd(String s) {
        String[] s1 = s.split(" ");
        return s1[s1.length - 1];
    }

    private String getStart(String s) {
        String[] s1 = s.split(" ");
        return s1[0];
    }

    @Test
    public void test() {
        String[] array = new String[]{"a", "b", "a"};

        beforeAndAfterPuzzles(array);
    }
}
